package com.yand.redis;


import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;

/**
 * redis 乐观锁的实现
 */
public class TransactionDemo {

     public static void main(String [] args){
         Jedis jedis = RedisUtil.getJedis();
         String userId = "abc";
         String key    = keyFor(userId);
         jedis.setnx(key, String.valueOf(5));
         System.out.println(doubleAccount(jedis, userId));
         RedisUtil.returnResource(jedis);


     }

     public static int doubleAccount(Jedis jedis, String userId){
         String key = keyFor(userId);
         while(true){
             jedis.watch(key);
             int value = Integer.parseInt(jedis.get(key));
             value *= 2;
             Transaction tx = jedis.multi();
             tx.set(key, String.valueOf(value));
             List<Object> res = tx.exec();
             if(res != null){
                 break;
             }
         }

         return Integer.parseInt(jedis.get(key));


     }






     public static String keyFor(String userId){

         return String.format("account_%s",userId);
     }



}
